﻿using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace sqlTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string connStr = "Server=localhost;UserId=root;Password=#Lmy960926;Database=myClass;pooling=false;CharSet=utf8;port=3306";//声明一个字符串用来存放连接数据库的信息
            MySqlConnection conn = null;
            try
            {
                conn = new MySqlConnection(connStr);//创建一个MySqlConnection对象
                conn.Open();//打开数据库
                MessageBox.Show("数据库连接成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库连接失败！" + ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connStr = "Server=localhost;UserId=root;Password=#Lmy960926;Database=myClass;pooling=false;CharSet=utf8;port=3306";//声明一个字符串用来存放连接数据库的信息
            MySqlConnection conn = null;
            string name = nameTextBox.Text.Trim();
            string studentId = studentIdTextBox.Text;
            try
            {
                conn = new MySqlConnection(connStr);//创建一个MySqlConnection对象
                conn.Open();//打开数据库
                string sql = "select * from students_information where 1=1";
                if(name != null&&name.Length != 0)
                {
                    sql += " and student_name like " + "\'%" + name + "%\'";
                }
                if(studentId != null&&studentId.Length != 0)
                {
                    sql += " and student_id =" + studentId;
                }
                Console.WriteLine("sql= " + sql);
                MySqlDataAdapter sda = new MySqlDataAdapter(sql,conn);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                dgvList.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败！" + ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }
    }
}
